package com.forezp.web;

import com.forezp.client.ProviderClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by forezp on 2019/5/11.
 */

@RestController
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProviderClient providerClient;

    AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 测试qps
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/hello")
    public String hello() throws InterruptedException {
        int l = atomicInteger.incrementAndGet() % 3;
        switch (l) {
            case 0: {
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println(LocalDateTime.now() + " => " + 100);
                break;
            }
            case 1: {
                TimeUnit.MILLISECONDS.sleep(400);
                System.out.println(LocalDateTime.now() + " => " + 400);
                break;
            }
            case 2: {
                TimeUnit.MILLISECONDS.sleep(500);
                System.out.println(LocalDateTime.now() + " => " + 500);
                break;
            }
            default:
        }
        return "hello";
    }

    @GetMapping("/hi-resttemplate")
    public String hiResttemplate() {
        return restTemplate.getForObject("http://nacos-provider/hi?name=resttemplate", String.class);

    }

    @GetMapping("/hi-feign")
    public String hiFeign() {
        return providerClient.hi("feign");
    }


    @PostConstruct
    public void init() {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> {
            /*while (true) {
                try {
                    System.out.println("返回：==> " + providerClient.hi("feign") + " ==> " + LocalDateTime.now());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }*/
        });

    }
}
